package org.fastsyncer.plugin.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.common.constant.ThirdpartyConstant;
import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.common.util.ApplicationUtil;
import org.fastsyncer.plugin.AbstractConvert;
import org.fastsyncer.plugin.impl.pool.DatabasePool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * <ul>
 * <dt>港中旅组织转换规则：</dt>
 *  <dl>
 *      <li>Parent_Node_Name值为空时,设置企业组织Parent_Id为默认值</li>
 *  </dl>
 * </ul>
 * 
 * @author AE86
 * @date 2018年03月08日 下午15:09:12
 * @version 1.0.0
 */
public class HongKongOrgConvertImpl extends AbstractConvert {

    private final Logger logger = LoggerFactory.getLogger(HongKongOrgConvertImpl.class);

    private final String PARENT_ID_VALUE = ApplicationUtil.getKey(ThirdpartyConstant.THIRDPARTY_HONGKONG_ORG_PARENT_ID);

    private final String ID = "ID";

    private final String PARENT_ID = "PARENT_ID";

    private final String BASEORG_PATH = "BASEORG_PATH";

    private Object id;

    private Object pid;

    private StringBuilder orgPath;

    /**
     * 根据企业组织ID查询BASEORG_PATH（企业组织路径）
     */
    private final String SQL_QUERY_BASEORG_ID = "SELECT BASEORG_PATH FROM SD_BASEORG WHERE IS_DELETED = '0' AND ID = ?";

    @Override
    public String getConvertName() {
        return "港中旅组织_企业组织转换";
    }

    @Override
    public void convert(MappingTask task, List<Map<String, Object>> source, List<Map<String, Object>> target) {
        if (null == target || target.isEmpty()) {
            return;
        }

        int size = target.size();
        Map<String, Map<String, Object>> kv = new HashMap<String, Map<String, Object>>(size);
        Map<String, Object> r;
        for (int i = 0; i < size; i++) {
            r = target.get(i);
            pid = r.get(PARENT_ID);
            if (null != pid) {
                //如果以-结尾,设置值为默认值
                if (pid.toString().trim().endsWith("-")) {
                    r.put(PARENT_ID, PARENT_ID_VALUE);
                }
            }

            id = r.get(ID);
            if (null != id) {
                kv.put(String.valueOf(id), r);
            }
        }

        // 计算企业组织路径
        for (int i = 0; i < size; i++) {
            r = target.get(i);
            // 递归拼接层级路径
            orgPath = this.getPath(kv, new StringBuilder(), r);
            
            // 20180413 因为星盾平台创建了一个默认港中旅节点,所以每条数据的path追加一个默认港中旅节点路径
            // /[默认港中旅节点]/迁移节点/子节点/...
            orgPath.insert(0, "#").insert(0, PARENT_ID_VALUE);
            r.put(BASEORG_PATH, orgPath);
        }

        // 标记回收
        id = null;
        pid = null;
        orgPath = null;
        r = null;
        kv = null;
    }

    @Override
    public void convert(MappingTask task, Map<String, Object> source, Map<String, Object> target, String event, Map<String, Object> beforeData) {
        if (null == target) {
            return;
        }
        // 排除删除操作
        if (ConnectorConstant.OPERTION_DELETE.equals(event)) {
            return;
        }

        DatabasePool pool = DatabasePool.getInstance();
        String uuid = pool.create(task.getTargetMapping());
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        try {
            // 转换数据
            this.execute(uuid, event, source, target);
        } catch (Exception e) {
            logger.info(e.getClass() + " >> " + e.getLocalizedMessage());
        } finally {
            pool.close(uuid);
        }
    }

    /**
     * 递归拼接层级路径
     * @param kv
     * @param orgPath
     * @param r
     * @return 层级路径
     */
    private StringBuilder getPath(Map<String, Map<String, Object>> kv, StringBuilder orgPath, Map<String, Object> r) {
        id = r.get(ID);
        if (null != id) {
            // b8d9f47e4f9c45aea02223e0ed800d55#
            orgPath.insert(0, "#").insert(0, id);
        }
        pid = r.get(PARENT_ID);
        if (null == pid) {
            return orgPath;
        }
        r = kv.get(pid);
        if (null == r) {
            return orgPath;
        }
        return getPath(kv, orgPath, r);
    }

    private void execute(String uuid, String event, Map<String, Object> source, Map<String, Object> target) {
        // 获取数据库连接
        DatabasePool pool = DatabasePool.getInstance();
        JdbcTemplate jdbc = pool.get(uuid);
        if (null == jdbc) {
            return;
        }

        pid = target.get(PARENT_ID);
        if (null != pid) {
            //如果以-结尾,设置值为null
            if (pid.toString().trim().endsWith("-")) {
                target.put(PARENT_ID, PARENT_ID_VALUE);
            }
        }

        // 递归拼接层级路径
        orgPath = this.getPath(jdbc, target);
        target.put(BASEORG_PATH, orgPath);

        // 标记回收
        id = null;
        pid = null;
        orgPath = null;
    }

    private StringBuilder getPath(JdbcTemplate jdbc, Map<String, Object> r) {
        orgPath = new StringBuilder();
        id = r.get(ID);
        if (null != id) {
            // b8d9f47e4f9c45aea02223e0ed800d55#
            orgPath.insert(0, "#").insert(0, id);
        }
        pid = r.get(PARENT_ID);
        if (null == pid) {
            return orgPath;
        }

        r = jdbc.queryForMap(SQL_QUERY_BASEORG_ID, new Object[] { pid });
        if (null == r) {
            return orgPath;
        }
        Object oPath = r.get(BASEORG_PATH);
        if (null != oPath) {
            orgPath.insert(0, oPath);
        }
        return orgPath;
    }

}
